<template>
  <div class="page-content">
    <table-search
      ref="tableSearch"
      title="采购单列表"
      :columns="columns"
      :api="getList"
      selection
      @selection-change="onSelectionChange"
    >
      <div slot="table-title" class="table-title">
        <el-button
          @click="onExportExcel()"
          size="medium"
          type="primary"
          plain
          :disabled="!selection.length"
          >导出所选列表{{
            selection.length ? `(${selection.length})` : ''
          }}</el-button
        >
      </div>

      <template #totalPrice="{ row }">
        <span class="red">{{ row.totalPrice | formatAmount }}</span>
      </template>
      <template #payState="{ row }">
        <div :class="{ green: row.payState === 4 }">
          {{ payStateMap[row.payState] }}
        </div>
      </template>

      <template #deliveryState="{ row }">
        <span :class="{ green: row.deliveryState === 3 }">{{
          deliveryStateMap[row.deliveryState]
        }}</span>
      </template>
      <template #cancelState="{ row }">
        <span :class="row.cancelState === 1 ? 'green' : 'red'">{{
          cancelStateMap[row.cancelState]
        }}</span>
      </template>
      <template #invoiceUrl="{ row }">
        <el-link v-if="row.invoiceUrl" type="primary" target="_blank" :href="row.invoiceUrl">查看发票</el-link>
      </template>

      <template #relateOrderIds="{ row }">
        <template v-if="!row.relateOrderIds">
          未关联
        </template>
        <el-popover
          v-else
          v-for="(text, index) in row.relateOrderIds.split(',')"
          :key="index"
          placement="top"
          trigger="hover"
          :content="text"
        >
          <el-tag
            slot="reference"
            size="mini"
            style="margin: 3px;max-width: 100%;overflow: hidden;text-overflow: ellipsis;"
          >
            {{text}}
          </el-tag>
        </el-popover>
      </template>

      <template #operate="{ row }">
        <el-link
          type="primary"
          @click="
            $router.push(`/admin/purchase/offline/detail/${row.purchaseNo}`)
          "
          >查看详情</el-link
        >

        <el-popconfirm
          v-if="
            row.payState === 2 && row.payType === 2 && row.cancelState === 1
          "
          title="确认结算集团采购订单？"
          @confirm="onOfflinePay(row)"
        >
          <el-link slot="reference" type="primary">付款</el-link>
        </el-popconfirm>
        <el-link
          type="primary"
          v-if="row.payState === 4 && row.payType === 2"
          @click="showPayVoucher(row.purchaseNo)"
          >付款单</el-link
        >
      </template>
    </table-search>
    <el-dialog title="付款单" :visible.sync="payVoucherObj.visible" width="50%">
      <div class="upload-box" v-if="!payVoucherObj.url">
        <el-upload
          style="margin-bottom: 100px"
          drag
          multiple
          action=""
          :http-request="uploadPayVoucher"
          :show-file-list="false"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将付款单拖到此处，或<em>点击上传</em>
          </div>
        </el-upload>
      </div>
      <div class="upload-box" v-else>
        <div class="download-box">
          <div class="title">
            <i class="el-icon-s-order yellow icon"></i>付款单
          </div>
          <span class="text"
            >上传成功：{{ payVoucherObj.createTime | formatDate }}</span
          >
        </div>
        <div class="btn-box">
          <el-upload
            style="display: inline-block; margin: 0 10px"
            name="file"
            action=""
            :show-file-list="false"
            :http-request="uploadPayVoucher"
          >
            <el-button :loading="uploadPayVoucherLoading" type="primary"
              >重新上传</el-button
            >
          </el-upload>
          <el-button type="primary" @click="downloadPayVoucher"
            >下载</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TableSearch from '@/components/TableSearch/TableSearch';
import { createTableColumns } from '@/components/TableSearch/utils';

import {
  payStateMap,
  deliveryStateMap,
  payTypeMap,
  cancelStateMap,
} from '@/config/purchase/offline';

import {
  pageList,
  offlinePay,
  uploadPayVoucher,
  exportUrl,
  getPayVoucher,
} from '@/api/purchase/offlineOrder';

export default {
  components: { TableSearch },

  data () {
    const { formatDate, map2Select, downLoadFile } = this.$util;

    return {
      columns: createTableColumns([
        [
          '创建时间',
          'createTime',
          {
            search: { key: 'startTime,endTime', sort: 9 },
            formatter: val => formatDate(val),
          },
        ],
        ['采购单号', 'purchaseNo', { search: true }],
        ['采购商用户名', 'purchaseName', { search: true }],
        ['订单总金额（元）', 'totalPrice', { align: 'right' }],
        ['发货状态', 'deliveryState', { search: map2Select(deliveryStateMap) }],
        ['支付状态', 'payState', { search: map2Select(payStateMap) }],
        ['支付方式', 'payType', { search: map2Select(payTypeMap), formatter: val => payTypeMap[val] }],
        ['作废状态', 'cancelState', { search: map2Select(cancelStateMap) }],
        ['发票', 'invoiceUrl'],
        ['关联订单号', 'relateOrderIds', { search: true, formatter: val => val ? val.split(',').join('\n') : '未关联' }],
        ['操作', 'operate'],
      ]),
      selection: [],
      downLoadFile,
      deliveryStateMap,
      payStateMap,
      payTypeMap,
      cancelStateMap,
      payVoucherObj: {
        visible: false,
        purchaseNo: null,
        url: null,
        createTime: null,
      },
      uploadPayVoucherLoading: false,
    };
  },

  methods: {
    async getList (pageIndex, pageSize, query) {
      const newQuery = {
        pageIndex,
        pageSize,
        ...query,
      };
      return await pageList(newQuery);
    },

    onSelectionChange (val) {
      this.selection = val;
    },

    onExportExcel () {
      const purchaseNos = this.selection.map(item => item.purchaseNo).join(',');
      if (!purchaseNos) {
        this.$message.error('请选择要导出的记录');
        return false;
      }
      this.$util.downloadFile(`${exportUrl}?purchaseNos=${purchaseNos}`);
    },

    async onOfflinePay (row) {
      this.$refs.tableSearch.showLoading();
      try {
        await offlinePay(row.purchaseNo);
        this.$refs.tableSearch.reload();
        this.$message.success('结算集团采购订单成功');
      } catch (error) {
        this.$refs.tableSearch.hideLoading();
      }
    },
    showPayVoucher (purchaseNo) {
      this.payVoucherObj.url = null;
      this.payVoucherObj.createTime = null;
      this.payVoucherObj.visible = true;
      this.payVoucherObj.purchaseNo = purchaseNo;
      this._showPayVoucher(purchaseNo);
    },
    async _showPayVoucher (purchaseNo) {
      const loading = this.$loading();
      try {
        const { url, createTime } = await getPayVoucher({ purchaseNo });
        if (url) {
          this.payVoucherObj.url = url;
          this.payVoucherObj.createTime = createTime;
        }
      } catch (error) {
        console.log(error);
      }
      loading.close();
    },
    async uploadPayVoucher (param) {
      this.uploadPayVoucherLoading = true;
      try {
        await uploadPayVoucher(param.file, this.payVoucherObj.purchaseNo);
        this.uploadPayVoucherLoading = false;
        this.$message.success('上传成功');
        this._showPayVoucher(this.payVoucherObj.purchaseNo);
      } catch (error) {
        console.error(error);
      }
    },
    downloadPayVoucher () {
      this.$util.downloadFile(`${location.origin}/api/purchase/offlineOrder/downloadPayVoucher?purchaseNo=${this.payVoucherObj.purchaseNo}`);
    },
  },
};
</script>

<style scoped lang="scss">
.table-title {
  flex: 1;
  text-align: right;
  margin: -10px 0;
}
.red {
  color: #e30000;
}
.green {
  color: #06b62d;
}
.blue {
  color: #2682e5;
}
.yellow {
  color: #e1c019;
}
.upload-box {
  margin: auto;
  width: 360px;
  background-color: #fff;
  .btn-box {
    width: 360px;
    display: flex;
    justify-content: space-around;
    margin: 40px 0;
  }
}
.download-box {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: center;
  position: relative;
  overflow: hidden;
  line-height: 50px;
  padding: 40px 0;
  .title {
    display: flex;
    align-items: center;
    justify-content: center;
    .icon {
      font-size: 24px;
    }
  }
  .text {
  }
}
</style>
